/****************************************************
 * @class SheetTemplateTreeGrid
 * @extends Ext.ux.tree.TreeGrid
 ***************************************************/
	SheetTemplateTreeGrid = Ext.extend(Ext.ux.tree.TreeGrid,{
		setTemplateWin: null,
		dataReferenceWindow: null,
		setRoleWin: null,
		constructor:function(config){
			Ext.apply(this,config);
			
			SheetTemplateTreeGrid.superclass.constructor.call(this, {
				id: 'sheetTemplate_tree_grid',
				loadMask: {msg: "Loading..."},
				width: 600,
				height: 300,
				border: false,
				enableDD: false,
				rootVisible: false,
				viewConfig: {forceFit: true},
		        columns:[{
		            header: "文档",
		            width: 350,
		            dataIndex: 'project'
		        },{
		            header: "表单模板",
		            width: 170,
		            dataIndex: 'template'
		        },{
		            header: "显示状态",
		            width: 60,
		            dataIndex: 'displayStatus',
		            tpl: new Ext.XTemplate('{[this.renderColor(values.displayStatus)]}', {
						renderColor: function(v) {
							if(v == "隐藏") return "<font color=red><i>"+v+"</i></font>";
			            	else return "<i>"+v+"</i>";
						}
					})
		        }],
		        dataUrl: '/pdm/category/getSheetTemplateTreeGrid.htm',
		        root: new Ext.tree.AsyncTreeNode({
		        	id: '40',
		            text: "root"
		        }),
				tbar:[{
					text: "调整",
					scope: this,
					iconCls: 'cls_doc_tmpl',
					menu: {
						items: [{
							id: 'set_sheet_template',
							text: "表单样式",
							iconCls: 'cls_doc_tmpl',
							scope: this,
							handler: function(){
								var cur_node = this.getSelectionModel().getSelectedNode();
								if( Ext.isEmpty(cur_node) || !cur_node.isLeaf() )
								{
									Ext.Msg.alert("提示", "请选择相应的文档");
								}else{
									var json = cur_node.toJsonString(null,
										function(key, val) {
											return (key == 'project' || key == 'template' || key == 'tmplId');
										}, {
											project: 'text',
											template: 'tmplName',
											tmplId: 'tmplId'
										}
									);
									var obj = eval("("+json+")");
									
									if( !this.setTemplateWin )
									{
										var templateGridPanel = new SetSheetTemplateGrid({id:"setSheetTemplateGrid", _cur_node_id: cur_node.id});
										this.setTemplateWin = new SetSheetTemplateWin({id:"setSheetTemplateWin", title: "调整["+obj.text+"]页面样式", setSheetTemplatePanel: templateGridPanel});
									}
									
									this.setTemplateWin.setTitle("调整["+obj.text+"]页面样式");
									this.setTemplateWin.show();
									
									this.setTemplateWin.load();
								}
							}
						},{
							text: "数据关联",
							iconCls: 'cls_doc_tmpl',
							scope: this,
							handler: function(){
								var cur_node = this.getSelectionModel().getSelectedNode();
								if(!cur_node){
									Ext.Msg.alert("提示","请先选择文档！");
								}else{
									if(cur_node.isLeaf())
									{
										var json = cur_node.toJsonString(null,
											function(key, val) {
												return (key == 'project'|| key == 'template'|| key == 'tmplId');
											}, {
												project: 'text',
												template: 'tmplName',
												tmplId: 'tmplId'
											}
										);
										var obj = eval("("+json+")");
										
										if(Ext.isEmpty(this.dataReferenceWindow))
										{
											this.dataReferenceWindow = new DataReferenceWindow({id: "win_DataReference"})
										}
										
										this.dataReferenceWindow.show();
										this.dataReferenceWindow.dataReferencePanel.masterAttrPanel.load(obj.tmplId);
										this.dataReferenceWindow.dataReferencePanel.masterAttrPanel.setTitle("["+obj.tmplName+"] 页面元素");
										
									}else{
										Ext.Msg.alert("提示","请先选择相应的文档");
									}
								}
							}
						}]
					}
				},{
					text: "编辑",
					scope: this,
					iconCls: 'cls_edit_project',
					menu: {
						items: [{
							text: "隐藏",
							scope: this,
							iconCls: 'light_bulb_off',
							tooltip: "隐藏相应的文档",
							handler: function(){
								var cur_node = this.getSelectionModel().getSelectedNode();
								if( !cur_node || !cur_node.isLeaf() )
								{
									Ext.Msg.alert("提示", "请选择相应文档!");
								}else{
									var json = cur_node.toJsonString(null,
										function(key, val) {
											return (key == 'project' || key == 'template' || key == 'tmplId' || key == 'validFlag');
										}, {
											project: 'text',
											template: 'tmplName',
											tmplId: 'tmplId',
											validFlag: 'valid'
										}
									);
									var obj = eval("("+json+")");
								
									if(obj.valid == "true")
									{
										Ext.MessageBox.show({
											title: "提示",
											msg: "您确认隐藏["+obj.text+"]吗？",
											buttons: Ext.MessageBox.YESNO,
											fn: function(btn){
												if(btn == "yes")
												{
													var hideMask = new Ext.LoadMask(Ext.getBody(), {
														msg: "表单隐藏中，请稍后...",
														removeMask: true
													});
													hideMask.show();
													
													Ext.Ajax.request({
														url: '/pdm/category/hideCategory.htm',
														method: 'post',
														params: {
															cate_id: cur_node.id,
															action: "hide"
														},
														success: function(response,options){
															hideMask.hide();
															cur_node.parentNode.reload(true, true);
														},
														failure: function(response){
															var result = Ext.decode(response.responseText).message;
															Ext.Msg.alert("信息:", result);
														}
													});
												}
												else return;
											}
										});
									}
								}
							}
						},{
							text: "显示",
							scope: this,
							iconCls: 'light_bulb_on',
							tooltip: "恢复显示相应的文档",
							handler: function()
							{
								var cur_node = this.getSelectionModel().getSelectedNode();
								if( !cur_node || !cur_node.isLeaf() )
								{
									Ext.Msg.alert("提示", "请选择相应文档!");
								}else{
									var json = cur_node.toJsonString(null,
										function(key, val) {
											return (key == 'project'|| key == 'template'|| key == 'tmplId'|| key == 'validFlag');
										}, {
											project: 'text',
											template: 'tmplName',
											tmplId: 'tmplId',
											validFlag: 'valid'
										}
									);
									var obj = eval("("+json+")");
									
									if(obj.valid == "false")
									{
										var hideMask = new Ext.LoadMask(Ext.getBody(), {
											msg: "表单恢复中，请稍后...",
											removeMask: true
										});
										hideMask.show();
										
										Ext.Ajax.request({
											url: '/pdm/category/hideCategory.htm',
											method: 'post',
											params: {
												cate_id: cur_node.id,
												action: "restore"
											},
											success: function(response,options){
												hideMask.hide();
												cur_node.parentNode.reload(true, true);
											},
											failure: function(response){
												var result = Ext.decode(response.responseText).message;
												Ext.Msg.alert("信息:", result);
											}
										});
									}
								}
							}
						}]
					}
				},"->",{
					text: "刷新",
					scope: this,
					iconCls: "cls_table_refresh",
					handler: function(){
						this.root.reload(true,true);
					}
				}]
			});
			
			this.on('click',function(node){
				document.getElementById("_selected_node_id").value = node.id;
				//document.getElementById("_selected_node_text").value = node.text;
				//alert(node.text);
		    });
		    
		    this.on('dblclick',function(node){
		    	
		    });
		}
	});
	
/****************************************************
 * @class SetSheetTemplateWin
 * @extends Ext.Window
 ***************************************************/
	SetSheetTemplateWin = Ext.extend(Ext.Window,{
		setSheetTemplatePanel: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			SetSheetTemplateWin.superclass.constructor.call(this, {
				layout: 'fit',
				width: 380,
				height: 480,
				resizable: false,
				modal: true,
				closeAction: 'hide',
				plain: true,
				buttonAlign: 'center',
				items: this.setSheetTemplatePanel,
				buttons: [{
					text: "确定",
					disabled: false,
					scope: this,
					handler: function()
					{
						var r = this.setSheetTemplatePanel.getSelectionModel().getSelected();
						
						if(!r){
							Ext.Msg.alert("提示","请单击选中表单模板！");
						}else{
							this.hide();
							
							Ext.Ajax.request({
								method: 'post',
								url: '/pdm/category/setCateTemplate.htm',
								params: {
									templateId: r.get("tmpl_id"),
									cateId: Ext.fly("_selected_node_id").dom.value,
									singleton: true
								},
								success: function(response,options){
									/*
									var result = Ext.decode(response.responseText).message;
									Ext.Msg.alert("信息:", result);
									*/
									var tg_cateModel = Ext.getCmp("sheetTemplate_tree_grid");
									var parentNode = tg_cateModel.getSelectionModel().getSelectedNode().parentNode;
									parentNode.reload(true,true);
								},
								failure: function(response){
									var result = Ext.decode(response.responseText).message;
									Ext.Msg.alert("信息:", result);
									return false;
								}
							});
						}
					}
				},{
					text: "关闭",
					scope: this,
					handler: function(){
						this.hide();
					}
				}]
			});
		},
		load: function(){
			this.setSheetTemplatePanel.load();
		}
	});
/****************************************************
 * @class SetSheetTemplateGrid
 * @extends Ext.grid.GridPanel
 ***************************************************/
	SetSheetTemplateGrid = Ext.extend(Ext.grid.GridPanel,{
		condition: null,
		store: null,
		cm: null,
		searchField: null,
		_cur_node_id: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.condition = {};
			this.condition.limit = 50;
			
			this.store = new Ext.data.Store({
			    baseParams: this.condition,   
				proxy: new Ext.data.HttpProxy({
					method: 'POST',
					url: '/pdm/category/getTemplateList.htm'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'totalProperty',
					root: 'root',
					id: 'tmpl_id'
				},[
					{name: 'tmpl_id'},
					{name: 'tmplName'},
					{name: 'creator'},
					{name: 'dateOfCreate'},
					{name: 'memo'}
				])
			});
			
			this.cm = new Ext.grid.ColumnModel([
		        {
		           header: "模板名称",
		           dataIndex: 'tmplName',
		           sortable: true,
		           width: 180
		        },{
		           header: "备注",
		           dataIndex: 'memo',
		           sortable: true,
		           width: 70
		        }]);
	        	        
			this.searchField = new Ext.ux.form.SearchField({store: this.store, width:200});
			
			SetSheetTemplateGrid.superclass.constructor.call(this, {
			    loadMask: {msg:'Loading...'},
			    viewConfig: {forceFit: true},
				region: 'center',
				border: false,
				height: 500,
				layout: 'fit',
				split: true,
				cls: 'x-rb',
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm,
				trackMouseOver: false,
				tbar: ["查询：",this.searchField],
				bbar: new Ext.PagingToolbar({
					pageSize: 50,
					store: this.store,
					displayInfo: true
				})
			});
			
			this.on('rowdblclick',function(grid,rowIndex,e){
				var r = grid.getSelectionModel().getSelected();
				
				var setTemplateWin = Ext.getCmp("setSheetTemplateWin");
				setTemplateWin.hide();
				
				Ext.Ajax.request({
					method: 'post',
					url: '/pdm/category/setCateTemplate.htm',
					params: {
						templateId: r.get("tmpl_id"),
						cateId: Ext.fly("_selected_node_id").dom.value
					},
					success: function(response,options){
						/*
						var result = Ext.decode(response.responseText).message;
						Ext.Msg.alert("信息:", result);
						*/
						var tg_cateModel = Ext.getCmp("sheetTemplate_tree_grid");
						var parentNode = tg_cateModel.getSelectionModel().getSelectedNode().parentNode;
						parentNode.reload(true,true);
					},
					failure: function(response){
						var result = Ext.decode(response.responseText).message;
						Ext.Msg.alert("信息:", result);
						return false;
					}
				});
			});
		},
		load: function()
		{
			this.store.load();
		}
	});

/****************************************************
 * @class DataReferenceWindow
 * @extends Ext.Window
 ***************************************************/
DataReferenceWindow = Ext.extend(Ext.Window,{
	dataReferencePanel: null,
	constructor: function(config){
		Ext.apply(this,config);
		
		this.dataReferencePanel = new DataReferencePanel({id: "pnl_DataReference"});
		
		DataReferenceWindow.superclass.constructor.call(this, {
			layout: 'form',
			width: 760,
			height: 480,
			modal: true,
			plain: true,
			closeAction: 'hide',
			buttonAlign: 'center',
			resizable: false,
			layout: 'fit',
			items: [this.dataReferencePanel],
			buttons: [{
			    text: "确定",
			    scope: this,
			    disabled: false,
			    handler: function(){
			    	var mastNode = Ext.getCmp("sheetTemplate_tree_grid").getSelectionModel().getSelectedNode();
			    	var masterData = this.dataReferencePanel.masterAttrPanel.getSelectionModel().getSelected();
			    	var refProjectTreeNode = this.dataReferencePanel.refProjectTree.getSelectionModel().getSelectedNode();
			    	var refData = this.dataReferencePanel.refAttrPanel.getSelectionModel().getSelected();
			    	
			    	if(Ext.isEmpty(masterData))
			    	{
			    		Ext.Msg.alert("提示","请选择页面元素");
			    		return;
			    	}
			    	else if(Ext.isEmpty(refData))
			    	{
			    		Ext.Msg.alert("提示","请选择需关联的页面元素");
			    		return;
			    	}
			    	else if(Ext.isEmpty(refProjectTreeNode))
			    	{
			    		Ext.Msg.alert("提示","请选择相应的项目");
			    		return;
			    	}
			    	
			    	var saveMask = new Ext.LoadMask(Ext.getBody(), {
						msg: "信息保存中，请稍后...",
						removeMask: true
					});
					saveMask.show();
			    	
			    	Ext.Ajax.request({
						method: 'post',
						url: '/pdm/sheet/setDataReference.htm',
						params: {
							masterNodeId: mastNode.id,
							masterAttrId: masterData.get("attr_id"),
							refNodeId: refProjectTreeNode.id,
							refAttrId: refData.get("attr_id")
						},
						success: function(response,options){
							var win = Ext.getCmp("win_DataReference");
							win.hide();
							
							saveMask.hide();
						},
						failure: function(response){
							var result = Ext.decode(response.responseText).message;
							Ext.Msg.alert("信息:", result);
							
							saveMask.hide();
							return false;
						}
					});
			    }
			},{
			    text: "关闭",
			    disabled: false,
			    scope: this,
			    handler: function(){
			    	this.hide();
			    }
			}]
		});
	}
});
	
/****************************************************
 * @class DataReferencePanel
 * @extends Ext.FormPanel
 ***************************************************/
DataReferencePanel = Ext.extend(Ext.FormPanel,{
	masterAttrPanel: null,
	refAttrPanel: null,
	refProjectTree: null,
	constructor: function(config){
		Ext.apply(this,config);
		
		this.masterAttrPanel = new UsedAttrsGrid({id: "pnl_MasterAttr", title: "页面元素"});
		this.refProjectTree = new RefProjectTreeGrid({title: "项目"});
		this.refAttrPanel = new UsedAttrsGrid({id: "pnl_RefAttr", title: "选择关联元素"});
		
		DataReferencePanel.superclass.constructor.call(this, {
			region: 'center',
			border: false,
			width: 720,
			height: 400,
			layout: 'column',
			viewConfig: {forceFit: true},
			buttonAlign: 'center',
			items: [{
				columnWidth: 0.34,
				layout: 'fit',
				border: true,
				height: 410,
				items: [this.masterAttrPanel]
			},{
				columnWidth: 0.01,
				layout: 'fit',
				border: false,
				height: 410
			},{
				columnWidth: 0.30,
				border: true,
				height: 410,
				layout: 'fit',
				items: [this.refProjectTree]
			},{
				columnWidth: 0.01,
				layout: 'fit',
				border: false,
				height: 410
			},{
				columnWidth: 0.34,
				height: 410,
				layout: 'fit',
				items:[this.refAttrPanel]
			}]
		});
	}
});

/****************************************************
 * @class UsedAttrsGrid
 * @extends Ext.grid.GridPanel
 ***************************************************/
	UsedAttrsGrid = Ext.extend(Ext.grid.GridPanel,{
		cm: null,
		store: null,
		condition: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.cm = new Ext.grid.ColumnModel([
				new Ext.grid.RowNumberer(),
				{header:"标签名称",dataIndex:"label_text", width: 50},
				{header:"排列序号",dataIndex:"sort_order", width: 40, sortable: true},
				{header:"显示方式",dataIndex:"data_type", width: 40}
			]);
			
			this.condition = {tmpl_id: 0};
			
			this.store = new Ext.data.Store({
			    baseParams: this.condition, 
			    proxy: new Ext.data.HttpProxy({
			    	method: 'POST',
					url: '/pdm/sheet/getTemplateAttributes.htm'
				}),
		        reader: new Ext.data.JsonReader({
					 totalProperty: 'totalProperty',
					 root: 'root',
					 id: 'attr_id'
				},[
					{name: 'attr_id'},
					{name: 'attr_name'},
					{name: 'del'},
					{name: 'label_text'},
					{name: 'sort_order'},
					{name: 'data_type'},
					{name: 'data_type_id'},
					{name: 'group_number'},
					{name: 'col_span'},
					{name: 'max_length'},
					{name: 'default_value'},
					{name: 'reference_attr'},
					{name: 'reference_attr_id'}
				])
			});
			
			this.store.load();
			
			UsedAttrsGrid.superclass.constructor.call(this, {
				region: 'center',
				split: true,
				stripeRows: true,
				loadMask: true,
				border: false,
				autoScroll: false,
				cls: 'x-rb',
				viewConfig: {forceFit: true},
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm
			});
		},
		load: function(c){
			this.condition.tmpl_id = c;
			this.store.load();
		}
	});

/****************************************************
 * @class RefProjectTreeGrid
 * @extends Ext.ux.tree.TreeGrid
 ***************************************************/
	RefProjectTreeGrid = Ext.extend(Ext.ux.tree.TreeGrid,{
		rootId: '40',
		rootName: 'root',
		constructor:function(config){
			Ext.apply(this,config);
			
			RefProjectTreeGrid.superclass.constructor.call(this, {
				width: 600,
				height: 300,
				border: false,
				enableDD: false,
				rootVisible: false,
				viewConfig: {forceFit: true},
		        columns:[{
		            header: "文件",
		            width: 350,
		            dataIndex: 'project'
		        }],
		        dataUrl: '/pdm/category/getSheetTemplateTreeGrid.htm',
		        root: new Ext.tree.AsyncTreeNode({
		        	id: this.rootId,
		            text: this.rootName
		        })
			});
			
			this.on('click',function(node){
				var refAttrPnl = Ext.getCmp("pnl_RefAttr");
				
				var json = node.toJsonString(null,
					function(key, val) {
						return (key == 'project'|| key == 'template'|| key == 'tmplId');
					}, {
						project: 'text',
						template: 'tmplName',
						tmplId: 'tmplId'
					}
				);
				var obj = eval("("+json+")");
				
				refAttrPnl.load(obj.tmplId);
		    });
		}
	});
		
	